import { createRouter, createWebHistory } from 'vue-router'
import { getCookie } from '@/utils/cookie'
import { ElMessage } from 'element-plus'

const LoginView = () => import(/** webpackChunkName: 'login' */ '@/views/Login/IndexView.vue')
const LeftMenuView = () => import(/** webpackChunkName: 'leftMenu' */ '@/views/Menu/IndexView.vue')
const UserView = () => import(/** webpackChunkName: 'user' */ '@/views/User/IndexView.vue')
const RightsView = () => import(/** webpackChunkName: 'rights' */ '@/views/Rights/IndexView.vue')
const RoleView = () => import(/** webpackChunkName: 'roles' */ '@/views/Roles/IndexView.vue')
const CatrogyView = () => import(/** webpackChunkName: 'category' */ '@/views/Category/IndexView.vue')
const GoodsView = () => import(/** webpackChunkName: 'goods' */ '@/views/Goods/IndexView.vue')
const AddGoodsView = () => import(/** webpackChunkName: 'addGoods' */ '@/views/Goods/components/AddGoods/IndexView.vue')
const ParamView = () => import(/** webpackChunkName: 'params' */ '@/views/Params/IndexView.vue')
const ReportView = () => import(/** webpackChunkName: 'report' */ '@/views/Report/IndexView.vue')



const routes = [
  { path: '/login', name: 'login', component: LoginView },
  { path: '/', component: LeftMenuView, children: [
    {path: '/users', name: 'users', meta: {isShouQuan: true}, component: UserView},
    {path: '/rights', name: 'rights', meta: {isShouQuan: true}, component: RightsView},
    {path: '/roles', name: 'roles', meta: {isShouQuan: true}, component: RoleView},
    {path: '/categories', name: 'category', meta: {isShouQuan: true}, component: CatrogyView},
    {path: '/goods', name: 'goods', meta: {isShouQuan: true}, component: GoodsView},
    {path: '/addGoods', name: 'addGoods', meta: {isShouQuan: true}, component: AddGoodsView},
    {path: '/params', name: 'params', meta: {isShouQuan: true}, component: ParamView},
    {path: '/reports', name: 'report', meta: {isShouQuan: true}, component: ReportView},
    { path: '/', redirect: '/users' },
    { path: '/:pathMatch(.*)*', redirect: '/users' }
  ]}
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, _, next) => {
  if(to.meta.isShouQuan && (getCookie('token') === undefined || getCookie('token') === null)) {
    ElMessage('请先登录')
    return next({path: '/login', query: {backTo: to.fullPath}})
  } else {
    next()
  }
})

export default router